import React from "react";
import AreaPicker from "@/components/Area/AreaPicker";
import type business from "@/types/business";
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import type { PickerValue } from 'antd-mobile/es/components/picker-view';

interface BusinessType extends business
{
    active:string[];
    code:string;
    password?:string;// 可填
}

interface FormType{
    id:number;
    mobile:string;
    nickname:string,
    email:string,
    gender:string,
    password?:string;// 可填
    code?:string;
    avatar?:File;
}

const Profile = () =>
{
    // 创建一个表单实例
    const [ form ] = React.UI.Form.useForm();

    const [business] = useState<BusinessType>({
        ...React.business,
        active: [React.business.province, React.business.city, React.business.district],
        code: React.business.district || React.business.city || React.business.province || '',
        email:React.business.email ? React.business.email : ''
    });

    // 控制地区显示隐藏
    const [AreaShow,SetAreaShow] = useState<boolean>(false);

    // 头像
    const [avatar,SetAvatar] = useState<ImageUploadItem[]>([
        {
            url:business.avatar_cdn
        }
    ]);

    // 确认选中地区
    const OnAreaConfirm = (values:PickerValue[],names:PickerValue[]) =>
    {
        const [province,city,district] = names;

        const RegionText = [];

        if(province)
        {
            RegionText.push(province);
        }

        if(city)
        {
            RegionText.push(city);
        }

        if(district)
        {
            RegionText.push(district);
        }

        // 更新表单字段值
        form.setFieldsValue({
            region_text:RegionText.join('-'),
            code:values[2] ? values[2] : (values[1] ? values[1] : values[0])
        });
    }

    // 表单提交
    const OnSubmit = async (values:BusinessType) =>
    {
        const params:FormType = {
            id:business.id,
            mobile:values.mobile,
            nickname:values.nickname,
            email:values.email,
            gender:values.gender
        }

        if(values.password)
        {
            params.password = values.password;
        }
        
        if(business.avatar && business.avatar instanceof File)
        {
            params.avatar = business.avatar;
        }

        if(values.code)
        {
            params.code = values.code;
        }

        const result = await React.http.upload('/business/profile',params);

        if(result.code === 1)
        {
            React.success(result.msg,() =>
            {
                React.Cookies.save('business',result.data,{path:'/'});

                React.business = result.data;

                React.navigate(-1);
            });
        }else{
            React.fail(result.msg);
        }
    }

    // 上传头像
    const OnUploadAvatar = (file:File) =>
    {
        // 把上传文件赋值给business
        business.avatar = file;

        return {
            url: URL.createObjectURL(file),
        }
    }

    // 删除图片
    const OnAvatarDel = () =>
    {
        business.avatar = '';
        SetAvatar([]);
    }

    return (
        <>
            {/* 地区组件 */}
            <AreaPicker active={business.active} visible={AreaShow} onClose={() => SetAreaShow(false)} onConfirm={OnAreaConfirm} />

            <React.UI.Form
                name="profile"
                layout="horizontal"
                mode="card"
                form={form}
                initialValues={business}
                onFinish={OnSubmit}
                footer={<React.UI.Button block type='submit' color='primary' size='large'>提交修改</React.UI.Button>}
            >
                {/* 头像 */}
                <React.UI.AutoCenter style={{margin: '30px 0px'}}>
                    <React.UI.ImageUploader value={avatar} onChange={SetAvatar} maxCount={1} upload={OnUploadAvatar} onDelete={OnAvatarDel} />
                </React.UI.AutoCenter>

                <React.UI.Form.Item name="nickname" label="昵称" rules={[{required: true, message: '请输入昵称'}]}>
                    <React.UI.Input placeholder="请输入昵称" />
                </React.UI.Form.Item>

                <React.UI.Form.Item
                    name='mobile'
                    label="手机号码"
                    rules={[
                        {required: true, message: '请填写手机号码'},
                        {pattern: /^1[356789]\d{9}$/, message: '请输入正确格式的手机号码'}
                    ]}
                >
                    <React.UI.Input placeholder="请输入手机号码" />
                </React.UI.Form.Item>

                <React.UI.Form.Item name="password" label="密码">
                    <React.UI.Input type="password" placeholder="请输入密码" />
                </React.UI.Form.Item>

                <React.UI.Form.Item name="email" label="邮箱" rules={[{ required: true }, { pattern: /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/, message: '邮箱格式不对' }]}>
                    <React.UI.Input placeholder="请输入邮箱" />
                </React.UI.Form.Item>

                <React.UI.Form.Item name="gender" label="性别" rules={[{ required: true }]}>
                    <React.UI.Radio.Group>
                        <React.UI.Space direction='horizontal'>
                            <React.UI.Radio value='0'>保密</React.UI.Radio>
                            <React.UI.Radio value='1'>男</React.UI.Radio>
                            <React.UI.Radio value='2'>女</React.UI.Radio>
                        </React.UI.Space>
                    </React.UI.Radio.Group>
                </React.UI.Form.Item>

                {/* 地区 */}
                <React.UI.Form.Item name="region_text" label="地区" onClick={() => SetAreaShow(true)}>
                    <React.UI.Input placeholder="请选择地区" readOnly  />
                </React.UI.Form.Item>

                {/* 地区码 隐藏域 */}
                <React.UI.Form.Item
                    name="code"
                    label="地区码"
                    hidden={true}
                >
                    <React.UI.Input placeholder="地区码" readOnly />
                </React.UI.Form.Item>
            </React.UI.Form>
        </>
    )
}

export default Profile;